//
//  BSMeViewController.m
//  01-BuDeJie
//
//  Created by 1 on 15/12/17.
//  Copyright © 2015年 xiaomage. All rights reserved.
//

#import "BSMeViewController.h"

#import "BSSettingTableViewController.h"
#import "BSMeCollectionViewCell.h"
#import <AFNetworking.h>
#import "BSMeCollectionCellItem.h"
#import <MJExtension.h>
#import <SafariServices/SafariServices.h>
#import "BSHtmlViewController.h"

static NSString *const ID = @"cell";
static  int const cols = 4;
static CGFloat const margin = 1;

#define  cellWH  ((BSScreenW - (cols - 1) * margin) / cols)

@interface BSMeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
/** dataArr----李明杰的框架会设置数据懒加载,就不需要设置数据懒加载问题*/
@property (nonatomic ,strong) NSMutableArray *dataArr;
/** collectionView*/
@property (nonatomic ,weak) UICollectionView *collectionView;
@end

@implementation BSMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//        self.view.backgroundColor = [UIColor blueColor];
   
    //1.设置导航栏
    [self setUpBarButtonItem];
    //2.设置 tableFooterVIew
    [self setUpFooterView];
  
    // 3.设置tableView背景色
    self.tableView.backgroundColor = BSColor(206, 206, 206);
    
    //4.创建数据
    [self loadData];
    
    // 5.调整每一组间距
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    

}
#pragma mark ---------------
#pragma mark - setUpBarButtonItem(设置底部的 tabBar)

-(void)setUpBarButtonItem{
    
    
    //设置右边的UIBarButtonItem
    
    UIBarButtonItem *settingItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"mine-setting-icon"] HighLightImage:[UIImage imageNamed:@"mine-setting-icon-click"] Target:self Action:@selector(setting)];
    UIBarButtonItem *nightItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"mine-moon-icon"] SelectedImage:[UIImage imageNamed:@"mine-moon-icon-click"] Target:self Action:@selector(night:)];
   

    self.navigationItem.rightBarButtonItems = @[settingItem,nightItem];
    
    //设置中间的标题
    self.navigationItem.title = @"我的";
}

#pragma mark ---------------
#pragma mark - setting (设置按钮点击动作)

-(void)setting{
    
    BSSettingTableViewController *vc = [[BSSettingTableViewController alloc]init];
    
    // 隐藏底部条:条件:在跳转之前设置
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}
                                  
                                  
-(void)night:(UIButton *)button{
    
    button.selected = !button.selected;
    
   BSFunc;                                   
}
#pragma mark ---------------
#pragma mark -setUpFooterView(设置底部 View)

-(void)setUpFooterView{
    //0.创建一个流水布局
    // 1.创建流水布局
    UICollectionViewFlowLayout *layout = ({
        
        // 1.创建流水布局
        UICollectionViewFlowLayout *layout =  [[UICollectionViewFlowLayout alloc] init];
        
        // 2.设置流水布局属性
        
        // 2.1设置cell尺寸
       
        layout.itemSize = CGSizeMake(cellWH,cellWH);
        
        // 2.2 设置cell之间间距
        layout.minimumInteritemSpacing = margin;
        layout.minimumLineSpacing = margin;
        
        layout;
    });

    
    // 2.创建UICollectionView
    UICollectionView *collectionView = ({
        
        // 1.创建UICollectionView
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, BSScreenW, 0) collectionViewLayout:layout];
        
        // 2.设置数据源 -> 要UICollectionView展示数据
        collectionView.dataSource = self;
        collectionView.delegate = self;
        // 3. 注册cell
//        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
        [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BSMeCollectionViewCell class]) bundle:nil]  forCellWithReuseIdentifier:ID];
        collectionView.backgroundColor = self.tableView.backgroundColor;
        //将 collectionView 传出去用于刷新数据
        self.collectionView = collectionView;
        
        //设置取消弹簧效果---设置不能滚动,弹簧效果自然就没有了
//        collectionView.bounces = NO;
        //设置 collectionView不让滚动
        collectionView.scrollEnabled = NO;
        
        collectionView;
        
    });
    
    //3.加到父控器中
    self.tableView.tableFooterView = collectionView;
   
}

#pragma mark ---------------
#pragma mark - UICollectionViewDataSource(设置数据源)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.dataArr.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    
    //由于是 IndexPath 所以使用 register 方法
    //这里创建的 cell 是带有 ID 的,
  BSMeCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    BSMeCollectionCellItem *item = self.dataArr[indexPath.row];
    cell.item = item;
    return cell;
}

#pragma mark ---------------
#pragma mark - loaddata(导入数据)
-(void)loadData{
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    // 4.2 拼接请求参数
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"a"] = @"square";
    param[@"c"] = @"topic";
    
    // 4.3 发送请求get
    [mgr GET:baseUrl parameters:param success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
                [responseObject writeToFile:@"/Users/chenbowen/Desktop/collectionV.plist" atomically:YES];
        //        NSLog(@"%@",responseObject);
        // 获取字典数组
        NSArray *dictArr = responseObject[@"square_list"];
        
        // 字典数组转模型数组
        self.dataArr =  [BSMeCollectionCellItem mj_objectArrayWithKeyValuesArray:dictArr];
//        NSLog(@"%@",self.dataArr);
        
        [self resolveData];
        // 刷新表格
        [self.collectionView reloadData];
       
        //=========给 tableviewFooterView 重新赋值============
        NSInteger count =  self.dataArr.count;
        NSInteger rows = (count - 1) / cols + 1;
        CGFloat collectionH = rows * cellWH;
        self.collectionView.height = collectionH;
         //=========给 tableviewFooterView 重新赋值============
        
        // 直接重修设置tableView的footView,tableView计算下直接滚动范围
        //下面会多出20的间距,这是由于 tableView 自己没有计算好,导致的
        self.tableView.tableFooterView = self.collectionView;
        
        [self.tableView reloadData];
//        NSLog(@"%f",self.tableView.contentSize.height);
//       NSLog(@"%f",CGRectGetMaxY(self.collectionView.frame));
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}
#pragma mark ---------------
#pragma mark - resolveData(补方块)

// 计算缺多少个 -> 怎么去补方块
- (void)resolveData
{
    NSInteger count =  self.dataArr.count;
    NSInteger extre = count % cols;
    if (extre) {
        extre = cols - extre;
        // 让显示的 cell 没有图片,标题,直接不赋值就可以
        for (int i = 0; i < extre; i++) {
            BSMeCollectionCellItem *item = [[BSMeCollectionCellItem alloc] init];
            [self.dataArr addObject:item];
        }
        
    }
}

#pragma mark ---------------
#pragma mark - delegate(didSelectItemAtIndexPath)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  
//    NSLog(@"%ld",(long)indexPath.item);

    
    // 获取模型
    BSMeCollectionCellItem *item = self.dataArr[indexPath.row];
    //    item.url
    if ([item.url hasPrefix:@"http"]) {
        // 需要跳转到网页
        BSHtmlViewController *htmlVC = [[BSHtmlViewController alloc] init];
        htmlVC.item = item;
        
        [self.navigationController pushViewController:htmlVC animated:YES];
        
        // 要在跳转之后,隐藏:只有跳转,才会添加为导航控制器的子控制器
        htmlVC.navigationController.navigationBarHidden = YES;
    }

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 获取cell
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSLog(@"%@",NSStringFromCGRect(cell.frame));

}
@end
